import { ApiRes, User, UserProfile } from '@/types/data'
import { ProfileAction, RootThunkAction } from '@/types/store'
import request from '@/utils/request'

export function getUser(): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<ApiRes<User>>('/user')

    const user = res.data.data

    dispatch({
      type: 'profile/set_user',
      payload: user
    } as ProfileAction)
  }
}

export const getUserProfile = (): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiRes<UserProfile>>('/user/profile')

    const userProfile = res.data.data
    dispatch({
      type: 'profile/set_user_profile',
      payload: userProfile
    } as ProfileAction)
  }
}

export function updateUserProfile(data: Partial<UserProfile>): RootThunkAction {
  return async (dispatch) => {
    await request.patch('/user/profile', data)

    // 重新获取最新信息
    dispatch(getUserProfile())
  }
}

export function updateUserPhoto(data: FormData): RootThunkAction {
  return async (dispatch) => {
    await request.patch('/user/photo', data)
    dispatch(getUserProfile())
  }
}
